import { useEffect, useRef } from 'react'
import THREEProject from '../utils/index'
import { GUI } from 'three/examples/jsm/libs/dat.gui.module'

const BoxBufferGeometry = () => {
  let scale = {
    y: 1,
    xz: 1
  }
  let translate = {
    translateY: 0
  }
  const can = useRef(null)
  const pro = new THREEProject()
  const { thr, renderer, scene, axes, camera, controls } = pro
  const gui = new GUI()
  let mesh = null
  gui.add(scale, 'y', -2, scale.y)
  gui.add(scale, 'xz', 0, 2)
  gui.add(translate, 'translateY', translate.translateY, 5)
  const init = () => {
    scene.add(axes)
    const boxGeometry = new thr.BoxGeometry(5,5,5)
    const boxMaterial = new thr.MeshBasicMaterial({
      color: 0x000077,
      opacity: .8,
      transparent: true
    })
    mesh = new thr.Mesh(boxGeometry, boxMaterial)
    scene.add(mesh)
    appendRenderDom()
    animate()
  }
  const appendRenderDom = () => {
    if(!can.current.children.length) {
      can.current.appendChild(renderer.domElement)
    }
  }

  const render = () => {
    controls.update()
    mesh.scale.y = scale.y
    mesh.scale.x = scale.xz
    mesh.scale.z = scale.xz
    mesh.position.y = translate.translateY
    renderer.render(scene, camera)
  }

  const animate = () => {
    requestAnimationFrame(animate)
    render()
  }

  useEffect(init, [])

  return (
    <div ref={can}></div>
  )
}

export default BoxBufferGeometry
export {
  BoxBufferGeometry
}